import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const NoticeSchema = new mongoose.Schema({
    sender: Object, // 如果是chat，需要给sender方便前端跳转
    receiverId: String,
    receiver: Object, // 行为者的头像
    url: String,
    msg: String,
    createTime: Number,
    type: String, // system, like, cmt, chat, others
    status: Number, // 0: 未读； 1: 已读
});

NoticeSchema.methods.saveNotice = function (notice, cb) {
    notice.createTime = moment().unix();
    this.model('notice').insertMany([notice], cb);
};

NoticeSchema.methods.getNotices = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const noticeModel = this.model('notice');
    if (leftQuery.createTime) {
        leftQuery.createTime = { $lt: leftQuery.createTime }
    }
    noticeModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        noticeModel.find(leftQuery).sort({status: 1, createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, notices) => cb(err, notices, count, hasMore));
    });
};

NoticeSchema.methods.getAllNotices = function (query, cb) {
    // this.model('notice').find(query, { name: 1, _id: 0 }, cb);
    this.model('notice').find(query, cb);
};

NoticeSchema.methods.getNotice = function (query, cb) {
    this.model('notice').findOne(query, cb);
};

NoticeSchema.methods.updateNotice = function (notice, cb) {
    const _id = notice._id;
    delete notice._id;
    this.model('notice').findOneAndUpdate({ _id }, { $set: notice }, cb);
};

NoticeSchema.methods.removeNotices = function (noticeIds, cb) {
    this.model('notice').remove({ _id: { $in: noticeIds } }, cb);
};

export default db.model('notice', NoticeSchema);